package com.lottery.im.module.chat.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.module.chat.presenter.UserProfilePresenter;
import com.lottery.im.module.chat.view.UserProfileView;
import com.lottery.im.module.tim.model.FriendProfile;
import com.lottery.im.module.tim.model.FriendshipInfo;
import com.lottery.im.module.tim.presenter.FriendshipManagerPresenter;
import com.lottery.im.module.tim.viewfeatures.FriendshipManageView;
import com.lottery.im.util.DateUtils;
import com.lottery.im.util.StatusBarHelper;
import com.lottery.im.util.transformations.GlideCircleBorderTransform;
import com.lottery.im.widget.ShSwitchView;
import com.lottery.im.widget.dialog.ConfirmWarnDialogBuilder;
import com.lottery.im.widget.dialog.EditDialogBuilder;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.ext.sns.TIMAddFriendRequest;
import com.tencent.imsdk.ext.sns.TIMFriendResult;
import com.tencent.imsdk.ext.sns.TIMFriendStatus;
import com.tencent.imsdk.ext.sns.TIMFriendshipManagerExt;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 其他用户资料 （好友、非好友）
 */
public class UserProfileFragment extends BaseSwipeFragment<UserProfilePresenter> implements
    UserProfileView, FriendshipManageView {

  private final static String ID_KEY = "ID_KEY";
  private final static String TYPE_KEY = "TYPE_KEY";

  public static UserProfileFragment create(String id) {
    UserProfileFragment fragment = new UserProfileFragment();
    Bundle b = new Bundle();
    b.putString(ID_KEY, id);
    fragment.setArguments(b);
    return fragment;
  }

  public static UserProfileFragment create(String id, int type) {
    UserProfileFragment fragment = new UserProfileFragment();
    Bundle b = new Bundle();
    b.putString(ID_KEY, id);
    b.putInt(TYPE_KEY, type);
    fragment.setArguments(b);
    return fragment;
  }

  @BindView(R.id.iv_portrait) ImageView mIvPortrait;
  @BindView(R.id.tv_tip) TextView mTvTip;
  @BindView(R.id.tv_name) TextView mTvName;
  @BindView(R.id.tv_id) TextView mTvId;
  @BindView(R.id.tv_nick_name) TextView mTvNickName;
  @BindView(R.id.tv_remark_name) TextView mTvRemarkName;
  @BindView(R.id.layout_remark_name) LinearLayout mLayoutRemarkName;
  @BindView(R.id.tv_reg_time) TextView mTvRegTime;
  @BindView(R.id.layout_reg_time) LinearLayout mLayoutRegTime;
  @BindView(R.id.layout_black_list) LinearLayout mLayoutBlackList;
  @BindView(R.id.btn_confirm) Button mBtnConfirm;
  @BindView(R.id.btn_del) Button mBtnDel;
  @BindView(R.id.sw_black) ShSwitchView mSwBlack;

  private FriendshipManagerPresenter friendshipManagerPresenter;

  private String mIdentify;
  private FriendProfile mProfile;
  private TIMUserProfile mUserProfile;

  private final static int REMARK_REQUEST_CODE = 888;

  private int mType = 0;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_user_profile;
  }

  @Override protected void initPresenter() {
    presenter = new UserProfilePresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {

    StatusBarHelper.setStatusBarLightMode(getActivity());
    friendshipManagerPresenter = new FriendshipManagerPresenter(this);
    if (null == getArguments()) {
      popBackStack();
    } else {
      mIdentify = getArguments().getString(ID_KEY);
      mType = getArguments().getInt(TYPE_KEY, 0);
      mTvId.setText(mIdentify);
      refreshUI();
      mSwBlack.setOnSwitchStateChangeListener(mOnSwitchStateChangeListener);
      if (mType == 1) {
        mLayoutBlackList.setVisibility(View.GONE);
      } else {

        if (!FriendshipInfo.getInstance().isFriend(mIdentify)) {
          TIMFriendshipManagerExt.getInstance().getBlackList(new TIMValueCallBack<List<String>>() {
            @Override
            public void onError(int i, String s) {
            }

            @Override
            public void onSuccess(List<String> ids) {
              if (ids.contains(mIdentify)) {
                mSwBlack.setOnSwitchStateChangeListener(null);
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                  mSwBlack.setOn(true);
                  mSwBlack.setOnSwitchStateChangeListener(mOnSwitchStateChangeListener);
                }, 300);
              }
            }
          });
        }
      }

      if (mIdentify.equals(MyApplication.getInstance().getUserInfo().getQqFeedBackName()) ||
          mIdentify.equals(MyApplication.getInstance().getUserInfo().getQqServiceName())){
        mLayoutBlackList.setVisibility(View.GONE);
      }


    }
  }

  @OnClick({ R.id.iv_back, R.id.btn_confirm, R.id.btn_del, R.id.layout_remark_name })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.layout_remark_name:
        startFragmentForResult(
            ModifySingleTextFragment.create(mIdentify, mTvRemarkName.getText().toString(),
                ModifySingleTextFragment.OpType.REMARKNAME), REMARK_REQUEST_CODE);
        break;
      case R.id.btn_confirm:
        if (mBtnConfirm.getText().toString().equals("发消息")) {
          // 发消息
          ChatActivity.navToChat(mActivity, mIdentify, TIMConversationType.C2C);
        } else {
          // 添加好友
          if (mType == 0) {
            addFriend();
          } else {
            delBlack();
          }
        }
        break;
      case R.id.btn_del:
        // 删除好友
        delFriend();
        break;
    }
  }

  /**
   * 刷新界面显示
   */
  private void refreshUI() {
    if (FriendshipInfo.getInstance().isFriend(mIdentify)) {
      // 好友
      mTvTip.setVisibility(View.GONE);
      mProfile = FriendshipInfo.getInstance().getProfile(mIdentify);
      mTvName.setText(mProfile.getNickName());
      Glide.with(this)
          .load(mProfile.getAvatarUrl())
          .apply(new RequestOptions()
              .bitmapTransform(new GlideCircleBorderTransform(
                  mActivity.getResources().getDimension(R.dimen.portrait_border_width),
                  ContextCompat.getColor(mActivity, R.color.white)))
              .placeholder(R.drawable.icon_conversation_de)
              .error(R.drawable.icon_conversation_de))
          .into(mIvPortrait);
      mTvNickName.setText(mProfile.getNickName());
      mLayoutRemarkName.setVisibility(View.VISIBLE);
      mLayoutRegTime.setVisibility(View.GONE);
      mTvRemarkName.setText(mProfile.getRemark());
      mBtnConfirm.setText("发消息");
      mBtnDel.setVisibility(View.VISIBLE);
    } else {
      // 非好友
      mTvTip.setVisibility(View.VISIBLE);
      mTvName.setText("陌生人");
      mLayoutRemarkName.setVisibility(View.GONE);
      mLayoutRegTime.setVisibility(View.VISIBLE);
      mBtnConfirm.setText("加好友");
      mBtnDel.setVisibility(View.GONE);
      if (null == mUserProfile) {
        presenter.getUsersProfile(mIdentify);
      } else {
        Glide.with(this)
            .load(mUserProfile.getFaceUrl())
            .apply(new RequestOptions()
                .bitmapTransform(new GlideCircleBorderTransform(
                    mActivity.getResources().getDimension(R.dimen.portrait_border_width),
                    ContextCompat.getColor(mActivity, R.color.white)))
                .placeholder(R.drawable.icon_conversation_de)
                .error(R.drawable.icon_conversation_de))
            .into(mIvPortrait);
        mTvNickName.setText(mUserProfile.getNickName());
        String bir = String.valueOf(mUserProfile.getBirthday());
        mTvRegTime.setText(DateUtils.strAllTime2Format(bir));
      }
    }

    if (mIdentify.equals(MyApplication.getInstance().getUserInfo().getQqServiceName())
        || mIdentify.equals(MyApplication.getInstance().getUserInfo().getQqFeedBackName())) {
      // 在线客服、投诉建议 不可以删除
      mBtnDel.setVisibility(View.GONE);
    }
  }

  private void delFriend() {
    ConfirmWarnDialogBuilder.getInstance(mActivity)
        .setContent("确定删除该好友吗？")
        .setCancel("取消", null)
        .setConfirm("确定", v -> {
          showLoadingDialog();
          friendshipManagerPresenter.delFriend(mIdentify);
        }).show();
  }

  private void addFriend() {

    if (mSwBlack.isOn()) {
      delBlack();
    } else {
      EditDialogBuilder.getInstance(mActivity)
          .setTitle("好友验证信息")
          .setHint("请输入验证信息")
          .setCancel("取消", null)
          .setConfirm("确定", new EditDialogBuilder.onEditClickListener() {
            @Override public void onEditClick(String content) {
              showLoadingDialog();
              friendshipManagerPresenter.addFriend(mIdentify, "", "", content);
            }
          }).show();
    }
  }

  private void delBlack() {

    ConfirmWarnDialogBuilder.getInstance(mActivity)
        .setContent("确定将该用户移出黑名单并添加为好友？")
        .setCancel("取消", v -> {
          mSwBlack.setOn(true);
          mSwBlack.setOnSwitchStateChangeListener(mOnSwitchStateChangeListener);
        })
        .setConfirm("确定", v -> {
          showLoadingDialog();
          TIMFriendshipManagerExt.getInstance().delBlackList(Collections.singletonList(mIdentify),
              new TIMValueCallBack<List<TIMFriendResult>>() {
                @Override public void onError(int i, String s) {
                  cancelLoadingDialog();
                  showToast("移出黑名单失败～");
                  mSwBlack.setOn(true);
                  mSwBlack.setOnSwitchStateChangeListener(mOnSwitchStateChangeListener);
                }

                @Override public void onSuccess(List<TIMFriendResult> timFriendResults) {

                  List<TIMAddFriendRequest> reqList = new ArrayList<>();
                  TIMAddFriendRequest req = new TIMAddFriendRequest(mIdentify);
                  req.setAddWording("");
                  req.setRemark("");
                  req.setFriendGroup("");
                  reqList.add(req);

                  TIMFriendshipManagerExt.getInstance().addFriend(reqList,
                      new TIMValueCallBack<List<TIMFriendResult>>() {
                        @Override public void onError(int i, String s) {
                          cancelLoadingDialog();
                          showToast("移出黑名单成功，添加好友失败～");
                        }

                        @Override public void onSuccess(List<TIMFriendResult> timFriendResults) {
                          cancelLoadingDialog();
                          showToast("移出黑名单成功～");
                          setFragmentResult(RESULT_OK, new Intent());
                          popBackStack();
                        }
                      });
                }
              });
        }).show();
  }

  ShSwitchView.OnSwitchStateChangeListener mOnSwitchStateChangeListener =
      new ShSwitchView.OnSwitchStateChangeListener() {
        @Override public void onSwitchStateChange(boolean isOn) {

          mSwBlack.setOnSwitchStateChangeListener(null);
          if (isOn) {
            presenter.addBlack(mIdentify);
          } else {
            delBlack();
          }
        }
      };

  @Override public void onAddFriend(TIMFriendStatus status) {
    cancelLoadingDialog();
    switch (status) {
      case TIM_ADD_FRIEND_STATUS_PENDING:
        showToast("请求已发送");
        break;
      case TIM_FRIEND_STATUS_SUCC:
        refreshUI();
        break;
      case TIM_ADD_FRIEND_STATUS_FRIEND_SIDE_FORBID_ADD:
        showToast("对方拒绝添加任何人为好友");
        break;
      case TIM_ADD_FRIEND_STATUS_IN_OTHER_SIDE_BLACK_LIST:
        showToast("您在对方的黑名单中");
        break;
      case TIM_ADD_FRIEND_STATUS_IN_SELF_BLACK_LIST:
        showToast("对方在您的黑名单中");
        break;
      default:
        showToast("添加好友失败,请稍后再试");
        break;
    }
  }

  @Override public void onDelFriend(TIMFriendStatus status) {
    switch (status) {
      case TIM_FRIEND_STATUS_SUCC:
        refreshUI();
        break;
      case TIM_FRIEND_STATUS_UNKNOWN:
        showToast("删除失败");
        break;
    }
    cancelLoadingDialog();
  }

  @Override public void onChangeGroup(TIMFriendStatus status, String groupName) {

  }

  @Override public void refreshUsersProfile(TIMUserProfile profile) {
    mUserProfile = profile;
    refreshUI();
  }

  @Override public void addBlackSuc() {
    popBackStack();
  }

  @Override public void addBlackFail() {
    new Handler(Looper.getMainLooper()).postDelayed(() -> {
      mSwBlack.setOn(false);
      mSwBlack.setOnSwitchStateChangeListener(mOnSwitchStateChangeListener);
    }, 300);
  }

  @Override protected void onFragmentResult(int requestCode, int resultCode, Intent data) {
    super.onFragmentResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
      if (requestCode == REMARK_REQUEST_CODE && null != data) {
        mTvRemarkName.setText(data.getStringExtra(ModifySingleTextFragment.INPUT_CONTENT_KEY));
      }
    }
  }

  @Override public void onResume() {
    super.onResume();
    StatusBarHelper.setStatusBarLightMode(getActivity());
  }
}
